<template>
    <div>
        <!-- Breadcrumb面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
</el-breadcrumb>

<!-- Card -->
<el-card class="box-card">
    <!-- 警告 -->
  <el-alert title="警告：你只能选择第三级分类" type="warning" show-icon :closable="false" ></el-alert>
  <!-- 三级选项菜单 -->
<el-row class="el-ops-row">
    <el-col>
    <span>分类菜单</span>
    <el-cascader v-model="selectedCatKeys" :options="catList" :props="cascaderCatProps" @change="handleChange"></el-cascader>
    </el-col>
</el-row>

  <!-- Tabs标签页 -->
  <el-tabs v-model="activeName" @tab-click="handleTabClick">
<!-- name="only"这里决定了，切换后activeName会被修改值为only -->

  <!-- 动态参数面板 -->
     <el-tab-pane label="动态参数" name="many">
   <!-- 添加属性按钮 -->
<el-button type="primary" size="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>

<el-table :data="manyTableData" border stripe>
  <!-- 展开行 -->
    <el-table-column type="expand">
   <template slot-scope="scope">
     <!-- 循环渲染的参数tag -->
     <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
<!-- 输入文本框 -->
     <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
<!-- new Tag按钮 -->
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
    <pre>{{scope.row}}</pre>
  </template>
    </el-table-column>


    <el-table-column type="index" label="#" ></el-table-column>
    <el-table-column prop="attr_name" label="属性名称" ></el-table-column>
      <el-table-column  label="操作">

    <template slot-scope="scope">
      <el-button type="primary" size="default" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
      <el-button type="danger" size="default" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
    </template>

  </el-table-column>
</el-table>
    </el-tab-pane>


    <el-tab-pane label="静态属性" name="only">
      <!-- 添加参数按钮 -->
<el-button type="primary" size="primary"  :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>


<!-- 静态属性列表 -->
<el-table  :data="onlyTableData" border stripe>
  <!-- 展开行 -->
    <el-table-column type="expand">
      <template slot-scope="scope">
          <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
    <pre>{{scope.row}}</pre>
    </template>
    </el-table-column>
    <el-table-column type="index" label="#" ></el-table-column>
  <el-table-column prop="attr_id" label="编号" ></el-table-column>
  <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
  <el-table-column  label="操作">
    <template slot-scope="scope">
      <el-button type="primary" size="default" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
      <el-button type="danger" size="default" icon="el-icon-delete">删除</el-button>
    </template>
  </el-table-column>
</el-table>
    </el-tab-pane>

  </el-tabs>
</el-card>

<!-- 添加参数Dialog -->
<el-dialog
  :title="'添加'+titleText"
  :visible.sync="addDialogVisible"
  width="50%"
  @close="addDialogClosed"
  >
<!-- Form验证表单 -->
<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="addForm.attr_name"></el-input>
  </el-form-item>
</el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
</el-dialog>


<!-- 修改参数的Dialog -->
<el-dialog
  :title="'修改'+titleText"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editDialogClosed"
  >
<!-- Form验证表单 -->
<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="editForm.attr_name"></el-input>
  </el-form-item>
</el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
</el-dialog>


</div>
</template>

<script>
export default {
  data() {
    return {
      catList: [],
      selectedCatKeys: [], //分类菜单选中的值
      cascaderCatProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyTableData: [], //categories参数为many的值 （动态参数）
      onlyTableData: [], //only静态属性
      activeName: "many", //Tabs选中的页签，默认请求的数据为静态属性many
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },

      // 修改参数dialog数据

      editDialogVisible: false,

      // 修改表单数据
      editForm: {
        attr_name: "",
      },

      // 修改表单规则
      editFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },

      //参数数据
      ParamsData: {},
      inputVisible: false,
      inputValue: "",
    };
  },

  methods: {
    //   获取分类列表
    async getCatList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("get请求Categories数据失败");
      }
      this.catList = res.data;
      console.log(this.catList);
      return this.$message.success("get请求Categories数据成功");
    },

    // cascader选项框 选中发生变化后 触发 改变选项后触发事件
    handleChange() {
      this.getParamsData();
    },

    // Tabs页签点击 切换页签
    handleTabClick() {
      this.getParamsData();
      console.log(this.activeName);
    },

    // 获取参数列表函数
    async getParamsData() {
      if (this.selectedCatKeys.length !== 3) {
        this.selectedCatKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[];
        return;
      }

      // 输出下是不是第三级
      console.log(this.selectedCatKeys);
      // 因为我们的后端接口需要id，所以需要获取id,与以往从data拿不同，cateID这里是个methods的方法，return过来
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status == !200) {
        return this.$message.error("get获取参数列表失败");
      }

      // 将attr_vals的字符串通过forEach+split 以空格为分割，转换为数组
      res.data.forEach((item) => {
        // 三元表达式判断是否为空
        item.attr_vals = item.attr_vals ? (item.attr_vals = item.attr_vals.split(" ")): []//如果不为空，split它的数组，通过tag输出，为空就[]
        item.inputVisible = false
        item.inputValue=''
        
      });
      console.log(res);
        
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 关闭DIalog重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }//
        );
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("post请求添加参数失败");
        } else {
          this.addDialogVisible = false;
          this.getParamsData();
          return this.$message.success("post请求添加参数成功");
        }
      });
    },

    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200)
        return this.$message.error("get获取查询参数信息失败");
      else {
        this.editForm = res.data;
        this.editDialogVisible = true;
        return this.$message.success("get获取查询参数信息成功");
      }
    },

    //关闭编辑弹窗后，重置清除内容
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 编辑静态属性/动态参数
    editParams(attr_id) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("put请求修改参数失败");
        }
        this.editDialogVisible = false;
        this.getParamsData();
        return this.$message.success("put请求修改参数成功");
      });
    },

    // 根据分类ID与scope.row.attr_id删除参数
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        "你确定删除该参数？ 是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消 ",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "取消删除",
        });
      });
      if (confirmResult) {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status !== 200) {
          this.$message({ type: "warning", message: "delete删除参数失败" });
        } else {
          this.$message.success("delete删除参数成功");
        }
        this.getParamsData();
      }
    },
// 点击+new input显示对话框，不要用this.inputVisible 会共享为true导致所有的都打开
    showInput(row) {
      // 让文本框获得焦点
 
      console.log(row);
      row.inputVisible = true;
      // $nextTick是当页面上元素被重新渲染后才执行的回调函数，保证先存在有这个input才能focus
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },

    // 通过splice删除参数的tag
   async handleClose(index,row){
      row.attr_vals.splice(index,1)
       const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
      {attr_name:row.attr_name,
      attr_sel:row.attr_sel,
      attr_vals:row.attr_vals.join(' ')})
        if(res.meta.status!==200){
          
            return this.$message.error('put删除参数属性值错误')
          }
          
            else return this.$message.success('put删除参数属性值成功')
    
    },

    //失去焦点和按下回车后
    async handleInputConfirm(row) {
      // trim()去除字符串两端的空格
      if(row.inputValue.trim().length===0)
      {
      row.inputValue=''
      row.inputVisible = false
      return//为空应当是return终止，不然会有空参数加入进去
      }
      // 若无return则输入正确内容，做正确的添加处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue=''
      row.inputVisible = false
      const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
      {attr_name:row.attr_name,
      attr_sel:row.attr_sel,
      attr_vals:row.attr_vals.join(' ')})
      // 之所以vals不同报400错误是因为没有join回去字符串
            console.log(res);
            // 
          if(res.meta.status!==200){
            return this.$message.error('put更改参数属性值错误')
          }
          
            else return this.$message.success('put更改参数属性值成功')
    },
  },

  created() {
    this.getCatList();
  },

  computed: {
    // 这里用来检测我们 选择分类菜单的是不是 length=3，也就是选对了没。如果不对按钮需要禁用 返回False  length如果是3则为 True
    isBtnDisabled() {
      if (this.selectedCatKeys.length !== 3) {
        return true;
      }
      return false;
    },
    //当前选中的第三级分类的ID
    cateId() {
      if (this.selectedCatKeys.length === 3) {
        return this.selectedCatKeys[2];
      }
      return null;
    },

    // DIalogTitle名
    titleText() {
      if (this.activeName === "only") {
        return "静态属性";
      } else return "动态参数";
    },
  },
};
</script>

<style lang="less" scoped>
.el-ops-row {
  margin: 10px 0;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin-left: 30px;
}
// 添加文本框大小
.input-new-tag{
  width:120px;
}
</style>